package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VideoApi;
import com.tanhua.dubbo.server.enums.CommentType;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.VideoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
@Slf4j
public class VideoService {
    @Autowired
    private PicUploadService picUploadService;
    @Reference(version = "1.0.0")
    private VideoApi videoApi;
    @Autowired
    protected FastFileStorageClient storageClient;
    @Autowired
    private FdfsWebServer fdfsWebServer;
    @Autowired
    private UserInfoService userInfoService;
    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;
    @Autowired
    private QuanZiService quanZiService;

    /**
     * 发布小视频
     *
     * @param picFile   视频封面文件
     * @param videoFile 视频文件
     * @return
     */
    public Boolean saveVideo(MultipartFile picFile, MultipartFile videoFile) {
        try {
            /* 分析：将视频封面文件保存在阿里云OSS中，视频文件保存在FastDFS中 */
            // 获取当前用户数据
            User user = UserThreadLocal.get();
            Video video = new Video();
            video.setUserId(user.getId()); // 发布视频用户id
            video.setSeeType(1); // 谁可看 默认公开

            /* 一、将视频封面文件保存在阿里云OSS中 */
            PicUploadResult picUploadResult = picUploadService.upload(picFile);
            if (StrUtil.isEmpty(picUploadResult.getName())) {
                // 封面上传失败
                return false;
            }
            video.setPicUrl(picUploadResult.getName()); // 视频封面文件url

            /* 二、视频文件保存在FastDFS中 */
            StorePath storePath = this.storageClient.uploadFile(videoFile.getInputStream(), // 文件流
                    videoFile.getSize(), // 文件大小
                    StrUtil.subAfter(videoFile.getOriginalFilename(), ".", true), // 文件后缀名
                    null // 元数据集
            );
            String videoUrl = this.fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
            video.setVideoUrl(videoUrl); // 视频文件url

            // 调用dubbo接口，将小视频对象保存再Mongodb中
            String videoId = this.videoApi.saveVideo(video);
            if (StrUtil.isNotEmpty(videoId)) {
                return true;
            }
        } catch (Exception e) {
            log.error("发布小视频失败！file = " + picFile.getOriginalFilename(), e);
        }
        return false;
    }

    /**
     * 查询小视频列表
     *
     * @param page     当前页
     * @param pageSize 页大小
     * @return
     */
    public PageResult queryVideoList(Integer page, Integer pageSize) {
        // 根据本地线程，获取当前用户信息
        User user = UserThreadLocal.get();

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        /* 一、查询小视频数据 */
        PageInfo<Video> pageInfo = this.videoApi.queryVideoList(user.getId(), page, pageSize);
        List<Video> videoList = pageInfo.getRecords();
        if (CollUtil.isEmpty(videoList)) {
            return pageResult;
        }

        /* 二、查询小视频对应的用户基本信息 */
        List<Object> userIdList = CollUtil.getFieldValues(videoList, "userId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByUserIdList(userIdList);
        Map<Long, UserInfo> userInfoMap = userInfoList.stream().collect(Collectors.toMap(UserInfo::getUserId, UserInfo -> UserInfo));

        /* 三、整合小视频以及对饮用户基本信息数据 */
        List<VideoVo> videoVoList = new ArrayList<>();
        VideoVo videoVo = null;
        for (Video video : videoList) {
            videoVo = new VideoVo();
            videoVo.setId(video.getId().toHexString()); // 主键id
            videoVo.setUserId(video.getUserId()); // 用户id
            videoVo.setCover(video.getPicUrl()); // 小视频封面文件url
            videoVo.setVideoUrl(video.getVideoUrl()); // 小视频文件url

            UserInfo userInfo = userInfoMap.get(video.getUserId());
            videoVo.setAvatar(userInfo.getLogo()); // 头像
            videoVo.setNickname(userInfo.getNickName()); // 昵称

            videoVo.setSignature("我就是我~"); //TODO 签名
            videoVo.setCommentCount(this.quanZiApi.queryCommentCount(video.getId().toHexString(), CommentType.COMMENT).intValue()); // 评论数
            videoVo.setHasFocus(this.videoApi.isFollowUser(user.getId(), videoVo.getUserId()) ? 1 : 0); // 是否关注
            videoVo.setHasLiked(this.quanZiApi.queryUserIsLikeOrLove(user.getId(), video.getId().toHexString(), CommentType.LIKE) ? 1 : 0); // 是否点赞（1是，0否）
            videoVo.setLikeCount(this.quanZiApi.queryLikeOrLoveCount(video.getId().toHexString(), CommentType.LIKE).intValue()); // 点赞数

            videoVoList.add(videoVo);
        }

        /* 四、封装数据并返回 */
        pageResult.setItems(videoVoList);
        return pageResult;
    }

    /**
     * 视频点赞
     *
     *
     * @param videoId 视频id
     * @return
     */
    public Long likeComment(String videoId) {
        // 根据本地线程，获取当前用户信息
        User user = UserThreadLocal.get();

        Boolean bool = this.quanZiApi.likeOrLoveComment(user.getId(), videoId, CommentType.LIKE);
        // 用户是否已经点赞，有则查询点赞数返回
        if (bool) {
            // 没有点赞
            return this.quanZiApi.queryLikeOrLoveCount(videoId, CommentType.LIKE);
        }
        return null;
    }

    /**
     * 取消点赞
     *
     * @param videoId 视频id
     * @return
     */
    public Long disLikeComment(String videoId) {
        // 根据本地线程，获取当前用户信息
        User user = UserThreadLocal.get();

        Boolean bool = this.quanZiApi.disLikeOrLoveComment(user.getId(), videoId, CommentType.LIKE);
        // 用户是否已经点赞，有则查询点赞数返回
        if (bool) {
            // 有点赞
            return this.quanZiApi.queryLikeOrLoveCount(videoId, CommentType.LIKE);
        }
        return null;
    }

    /**
     * 评论列表
     * @param videoId
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryCommentList(String videoId, Integer page, Integer pageSize) {
        return this.quanZiService.queryCommentList(videoId, page, pageSize);
    }

    /**
     * 提交评论
     * @param videoId
     * @param content
     * @return
     */
    public Boolean saveComment(String videoId, String content) {
        return this.quanZiService.saveComments(videoId, content);
    }


    /**
     * 关注⽤户
     *
     * @param userId
     * @return
     */
    public Boolean followUser(Long userId) {
        User user = UserThreadLocal.get();
        return this.videoApi.followUser(user.getId(), userId);
    }
    /**
     * 取消关注
     *
     * @param userId
     * @return
     */
    public Boolean disFollowUser(Long userId) {
        User user = UserThreadLocal.get();
        return this.videoApi.disFollowUser(user.getId(), userId);
    }
}
